using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;
using System.Data.SqlClient;

namespace servermon_library
{
	public class ServerManager
	{
		private Dictionary<Int32, Server> servers = new Dictionary<int, Server>();
		public ServerManager()
		{
			getServersFromDB(); // fill server array
		}

		private void getServersFromDB()
		{
			try
			{
				DataTable serverTable = DbHandler.ExecSQLReturnDT("SELECT * FROM servers");
				foreach (DataRow row in serverTable.Rows)
				{
					Server server = new Server((Int32)row[0], (String)row[1], (String)row[2]);
					servers.Add((Int32)row[0], server);
				}
			}
			catch (Exception ex)
			{
				throw new Exception("There was a problem fetching the serverlist:\n" + ex.Message);
			}
		}
		public Server[] GetServers() // return array with all servers
		{
			Server[] serverArray = new Server[servers.Count];
			servers.Values.CopyTo(serverArray, 0);
			return serverArray;
		}

		public Server GetServerById(Int32 id)
		{
			return servers[id];
		}

		public void UpdateLastSeen(Int32 id, String time)
		{

			servers[id].lastseen = time;
		}

		public Boolean AddServer(Server newServer)
		{
			servers.Add(newServer.serverid, newServer);

			// add server to database
			try
			{
				Int32 result = DbHandler.ExecSQLNonQuery(@"INSERT INTO servers (Name, adress) VALUES ('" + newServer.servername + "', '" + newServer.serverip + "');");
				return result > 0 ? true : false;
			}
			catch (Exception ex)
			{
				throw new Exception("There was a problem connecting to the Database:\n" + ex.Message);
			}
		}

		public Boolean RemoveServer(Int32 id)
		{
			servers.Remove(id);
			// remove server from DB
			try
			{
				Int32 result = DbHandler.ExecSQLNonQuery(@"DELETE * FROM servers WHERE ID = " + id + ";");
				return result > 0 ? true : false;
			}
			catch (Exception ex)
			{
				throw new Exception("There was a problem connecting to the Database:\n" + ex.Message);
			}
		}
	}
}
